package com.j180.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan("com.j180.dao")
public class MybatisConfig {
    @Bean
    public DataSource dataSource(){
        DruidDataSource dds = new DruidDataSource();
        dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dds.setUrl("jdbc:mysql://localhost:3306/pet?useSSL=false&serverTimezone=Asia/Shanghai");
        dds.setUsername("root");
        dds.setPassword("root");
        return dds;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
        sfb.setDataSource(this.dataSource());
        sfb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*.xml"));
        // 设置别名
        sfb.setTypeAliasesPackage("com.j180.bean");
        // 配置log4j
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(Log4jImpl.class);
        sfb.setPlugins(new Interceptor[] {getPageInterceptor()});
        return sfb.getObject();
    }

    // 配置事物管理
    @Bean
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(this.dataSource());
    }

    // PageHelper 分页相关配置
    @Bean
    public PageInterceptor getPageInterceptor(){
        PageInterceptor pageIntercptor=new PageInterceptor();
        Properties properties=new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("reasonable", "true");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageIntercptor.setProperties(properties);
        return pageIntercptor;
    }
}
